package cn.livingCloud.controller.core.validator;

import cn.livingCloud.context.Config;
import cn.livingCloud.dto.MemberListDto;
import cn.livingCloud.dto.front.SelfBindingFrontFormDto;
import cn.livingCloud.entity.core.EmployeeWechat;
import cn.livingCloud.entity.user.Member;
import cn.livingCloud.repository.EmployeeWechatMapper;
import cn.livingCloud.repository.MemberMapper;
import cn.livingCloud.utils.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import java.util.List;

/**
 * Created by DingJie on 2016/6/24.
 */
@Component
public class SelfBindingFrontFormDtoValidator implements Validator {
    @Autowired
    private EmployeeWechatMapper wechatMapper;
    @Autowired
    private MemberMapper memberMapper;

    @Override
    public boolean supports(Class<?> aClass) {
        return SelfBindingFrontFormDto.class.equals(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        SelfBindingFrontFormDto formDto = (SelfBindingFrontFormDto) o;
        Member member = testMember();
        List<EmployeeWechat> byMemberUuid = wechatMapper.findByMemberUuid(member.getUuid());
        if (byMemberUuid.size() > 0) {
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "EmpWe", null, "当前微信已绑定");
            return;
        }
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "deptName", null, "部门名称不能为空");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "employeeName", null, "员工姓名不能为空");
    }

    @Deprecated
    private Member testMember() {
        //如果是测试模式就拿member表中的第一条数据
        if (Config.ENVIRONMENT.equals("development")) {
            MemberListDto listDto = new MemberListDto();
            List<Member> list = memberMapper.getList(listDto);
            return list.get(0);
        }
        return (Member) SessionUtils.getCurrentMember();
    }
}
